package top.glimpse.constantcall;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class MainActivity extends AppCompatActivity {

    private boolean isCall = false;
    private EditText et_phonenumber;
    private TextView tv_tip;
    private TextView tv_hint;
    private String number;
    private int freq = new Random().nextInt(5) + 1;
    private boolean isRandom = false;
    private Context mContext = this;
    private boolean isAutoStop = true;
    private Thread callThread;
    private Spinner mySpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_phonenumber = (EditText) findViewById(R.id.phonenumber);
        tv_tip = (TextView) findViewById(R.id.tip);
        tv_hint = (TextView) findViewById(R.id.hint);
        tv_hint.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tv_hint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "假如再碰不见你们，祝你们早安、午安、晚安。", Toast.LENGTH_LONG).show();
            }
        });

        initSpinner();

        //点击拨打按钮
        final Button btn_call = (Button) findViewById(R.id.btn_call);
        btn_call.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                number = et_phonenumber.getText().toString();


                if (!isCall) {
                    //如果点了开始,本来是不打的状态.
                    if (!TextUtils.isEmpty(number)) {
                        mySpinner.setEnabled(false);
                        et_phonenumber.setEnabled(false);

                        if (!isCall) {
                            callThread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    constantCall();
                                }
                            });
                            callThread.start();
                        }
                        isCall = !isCall;
                        btn_call.setText(isCall ? "停止" : "开始");
                    }
                    else {
                        Toast.makeText(mContext, "先输入正确的电话号码再点~", Toast.LENGTH_SHORT).show();
                    }
                }
                else {
                    //如果点了暂停,本来是打得状态
                    isCall = !isCall;
                    btn_call.setText(isCall ? "停止" : "开始");
                    mySpinner.setEnabled(true);
                    et_phonenumber.setEnabled(true);
                    callThread.interrupt();
                }
            }
        });

        //选择联系人
        ImageView numberPicker = (ImageView) findViewById(R.id.number_picker);
        numberPicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 1);
            }
        });
    }

    private void initSpinner() {
        List<String> list = new ArrayList<>();
        list.add("随机（1-5分钟）");
        list.add("1分钟");
        list.add("2分钟");
        list.add("3分钟");
        list.add("4分钟");
        list.add("5分钟");
        list.add("6分钟");
        list.add("7分钟");
        list.add("8分钟");
        list.add("9分钟");
        list.add("10分钟");
        mySpinner = (Spinner) findViewById(R.id.freq_spinner);
        // 第二步：为下拉列表定义一个适配器，这里就用到里前面定义的list。
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
        // 第三步：为适配器设置下拉列表下拉时的菜单样式。
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 第四步：将适配器添加到下拉列表上
        mySpinner.setAdapter(adapter);
        // 第五步：为下拉列表设置各种事件的响应，这个事响应菜单被选中
        mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                if (arg2 == 0) {
                    freq = new Random().nextInt(5) + 1;
                    isRandom = true;
                } else {
                    freq = arg2;
                    isRandom = false;
                }
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }

    private void constantCall() {
        //用intent启动拨打电话
        while(isCall) {
            if (!TextUtils.isEmpty(number)) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
                startActivity(intent);
            }
            if (isRandom) {
                freq = new Random().nextInt(5) + 1;
            }
            try {
                Thread.sleep(1000 * 60 * freq);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Uri contactData = data.getData();
                    Cursor cursor = managedQuery(contactData, null, null, null,
                            null);
                    cursor.moveToFirst();
                    String num = this.getContactPhone(cursor);
                    et_phonenumber.setText(num);
                }
                break;

            default:
                break;
        }
    }

    private String getContactPhone(Cursor cursor) {
        // TODO Auto-generated method stub
        int phoneColumn = cursor
                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        int phoneNum = cursor.getInt(phoneColumn);
        String result = "";
        if (phoneNum > 0) {
            // 获得联系人的ID号
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            String contactId = cursor.getString(idColumn);
            // 获得联系人电话的cursor
            Cursor phone = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                            + contactId, null, null);
            if (phone.moveToFirst()) {
                for (; !phone.isAfterLast(); phone.moveToNext()) {
                    int index = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    return phone.getString(index);
                }
                if (!phone.isClosed()) {
                    phone.close();
                }
            }
        }
        return result;
    }
}
